package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.mapper.BrandMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

@Service
public class BrandService {
    @Autowired
    private BrandMapper brandMapper;

    public PageResult<BrandDTO> page(int page, int rowsPerPage, Boolean descending, String sortBy, String key) {
        // 分页
        PageHelper.startPage(page, rowsPerPage);
        // 过滤条件
        Example example = new Example(Brand.class);
        if (StringUtils.isNoneBlank(key)) {
            example.createCriteria().orLike("name", "%" + key + "%")
                    .orEqualTo("letter", key);
        }
        // 排序
        if (StringUtils.isNoneBlank(sortBy)) {
            String byClause = sortBy + (descending ? " DESC" : " ASC");
            example.setOrderByClause(byClause);
        }
        // 查询
        List<Brand> brandList = brandMapper.selectByExample(example);
        // 判断是否为空
        if (CollectionUtils.isEmpty(brandList)) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        // 完成城数据转换
        List<BrandDTO> brandDTOList = BeanHelper.copyWithCollection(brandList, BrandDTO.class);
        // 组合返回给前端的 PageResult
        PageResult<BrandDTO> pageResult = new PageResult<>();
        pageResult.setItems(brandDTOList);
        // 获取分页助手的分页对象
        PageInfo<Brand> pageInfo = new PageInfo<>(brandList);
        pageResult.setTotal(pageInfo.getTotal());
        //pageResult.setTotalPage((int) (pageInfo.getTotal()/rowsPerPage+1));
        //返回
        return pageResult;
    }

    @Transactional
    public void saveBrand(BrandDTO brandDTO, List<Long> cids) {
        // 新增品牌,先转换成po
        Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);
        brand.setId(null);
        int count = brandMapper.insertSelective(brand);  // 用 insertSelective 就可以自动填 brandDTO中没有的值
        if (count != 1) {
            // 新增失败，抛出异常
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        //去中间表存
        count = brandMapper.insertCategoryBrand(brand.getId(), cids);
        if (count != cids.size()) {
            // 新增失败，抛出异常
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    @Transactional
    public void deleteById(Long id) {
        //删除brand表
        int count = brandMapper.deleteByPrimaryKey(id);
        if (count != 1) {
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }

        count = brandMapper.deleteCategoryBrand(id);
    }

    @Transactional
    public void updateBrand(BrandDTO brandDTO, List<Long> cids) {
        // 修改品牌,先转换成po
        Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);
        int count = brandMapper.updateByPrimaryKey(brand);
        if(count != 1){
            // 更新失败，抛出异常
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 删除中间表数据
        brandMapper.deleteCategoryBrand(brand.getId());

        //去中间表存
        count = brandMapper.insertCategoryBrand(brand.getId(), cids);
        if (count != cids.size()) {
            // 新增失败，抛出异常
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }

    public BrandDTO queryById(Long brandId) {
        Brand brand = brandMapper.selectByPrimaryKey(brandId);
        if (brand == null) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyProperties(brand, BrandDTO.class);
    }

    public List<BrandDTO> queryByCategoryId(Long id) {
        List<Brand> brandList = brandMapper.queryByCategoryId(id);
        return BeanHelper.copyWithCollection(brandList, BrandDTO.class);
    }

    //根据Ids查询品牌信息
    public List<BrandDTO> queryByIds(List<Long> ids) {
        List<Brand> list = brandMapper.selectByIdList(ids);
        // 判断是否为空
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, BrandDTO.class);
    }
}
